var roleArray = new Array();//权限左右下拉框值

$(function(){
	$("#user-role-selecte").multiSelect({
		  selectableHeader: "<div class='custom-header' style='text-align:center;'>待选</div>",
		  selectionHeader : "<div class='custom-header' style='text-align:center;'>已选</div>",
		  afterSelect: function(values){//向roleArray保存选中值
			  roleArray.push(values.toString());
		  },
		  afterDeselect: function(values){//遍历roleArray删除选中值
			  for(index in roleArray){
				  if(roleArray[index]==values){
					  roleArray.splice(index,1);
				  }
			  }
		  }
	});
	loadTableInfo();
	loadUserRoleSelect();
});

//加载 talbe
function loadTableInfo(){
	var table = $('#tableinfo').DataTable();
	$('#tableinfo').dataTable({
		"processing": true,
        "serverSide": true,
        "ordering": false,
		"dom": '<"top"><"toolbar">rt<"bottom"lp><"clear">',//table布局(可更换位置)：r加载等待显示信息|t表格|l每页显示多少|p分页按钮|f搜索框
	    "destroy": true,//每次加载，销毁原有table
        "ajax": $.ctx + "/sysuser/findByPage.do",
        "columns": [
            { "data": null },
            { "data": "account" },
            { "data": "name" },
            { "data": "status" },
            { "data": "roleNames" },
            { "data": null }
        ],
        "columnDefs": [
			   {"targets": 0,
			    "render" : function(data, type, row, where) {
					return '<input type="checkbox" name="id" value="'+data.id+'" />';}
			   },
               {"targets": 3,
            	"render" : function(data, type, row, where) {
            		return row.status==0?"正常":"停用";}
               },
               {"targets": 5,
                "render" : function(data, type, row, where) {
                	var html = '';
                	html += '<button type="button" class="btn btn-default btn-xs" onclick="javascript:delAction('+data.id+');">删除</button>';
                    return html;}
               }
        ]
    });
	//增加自定义按钮
//	var buttonhtml  = '&nbsp;<button type="button" class="btn btn-success" onclick="createDialog()" >添加</button>';
//	 	buttonhtml += '&nbsp;<button type="button" class="btn btn-success" onclick="updateDialog()" >修改</button>';
//	$("div.toolbar").html(buttonhtml);
}

//加载 - 权限列表
function loadUserRoleSelect(){
	$.ajax({
		url : $.ctx + "/sysrole/getSysRoleForUserPage.do",
		type : "post",
		dataType : "json",
		success : function(List){
			$.each(List, function(n, role) {
				$('#user-role-selecte').multiSelect('addOption', { value: role.id, text: role.name, index: 0 });
			});
		}
	});
}

//修改
function updateDialog(){
	$("#fm-modal-label").html("修改用户");
	var chk_value = []; 
	$('input[name="id"]:checked').each(function(){ 
		chk_value.push($(this).val()); 
	}); 
	if (chk_value.length > 1 || chk_value.length == 0) {
		alert('请选择一行');
		return;
	}
	$("#tableinfo [name='id']").removeAttr("checked");//取消全选 
	$.ajax({
		url : $.ctx + "/sysuser/getsysuser.do",
		type : "post",
		data : {
			"userId" : chk_value[0]
		},
		dataType : "json",
		success : function(result){
			//将数据放入表格，并呈现
			$("#fm #account").val(result.account);
			$("#fm #name").val(result.name);
			$("#fm #password").val(result.password);
			$("#fm #user-role-selecte option").removeAttr("selected");//取消权限全选 
			$.each(result.roleList, function(n, role) {
				$.each($("#fm #user-role-selecte option"), function(n, option) {
					if($(option).val()==role.id){
						$(option).attr("selected",true);
					}
				});
			});
			$("#user-role-selecte").multiSelect('refresh');
			$("#saveSysRolePage").modal("show");
		}
	});
}

//添加
function createDialog(){
	$("#fm-modal-label").html("添加用户");
	$("#saveSysRolePage").modal("show");
}

//添加
function save(){
	$.ajax({
		url : $.ctx + "/sysuser/save.do",
		type : "post",
		data : {
			"account" : $("#fm #account").val(),
			"name" : $("#fm #name").val(),
			"password": $("#fm #password").val(),
			"roles" : roleArray.toString()
		},
		dataType : "json",
		success : function(result){
			if (result.msg == '操作成功') {
				$("#saveSysRolePage").modal("hide");
				loadTableInfo();
				toastr.success(result.msg);
			}else{
				toastr.warning(result.msg);
			}
		}
	});
}